package com.sakiko.audiobook.search.receiver;

import com.rabbitmq.client.Channel;
import com.sakiko.audiobook.common.rabbit.constant.MqConst;
import com.sakiko.audiobook.common.result.Result;
import com.sakiko.audiobook.search.service.SearchService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * projectName: com.sakiko.audiobook.search.receiver
 *
 * @author: sakiko
 * time: 2025/9/23 12:42
 * description: 批量上架 消息接收
 * 系统自动上架-下架:
 * 单张专辑操作: 保存专辑 or 修改专辑
 * 批量操作:
 * 文件读取、后台选择等等
 */
@Component
public class SearchReceiver {

    @Autowired
    private SearchService searchService;

    /**
     * 监听上架
     *
     * @param albumId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_UPPER
    ))
    public void upperAlbum(Long albumId, Message message, Channel channel) {
        try {
            if (null != albumId) {
                // 调用 service
                searchService.upperAlbum(albumId);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        // 手动确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 监听下架
     *
     * @param albumId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_LOWER
    ))
    public void lowerAlbum(Long albumId, Message message, Channel channel) {
        try {
            if (null != albumId) {
                // 调用 service
                searchService.lowerAlbum(albumId);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        // 手动确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
